package com.tubang.logistics.controller.order;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.tubang.common.constant.Constants;
import com.tubang.common.util.*;
import com.tubang.component.entity.AddressEntity;
import com.tubang.component.service.IAddressService;
import com.tubang.component.util.RequestUtil;
import com.tubang.logistics.entity.*;
import com.tubang.logistics.service.*;
import com.tubang.logistics.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 物流公司运单 前端控制器
 * </p>
 *
 * @author wsl
 * @since 2017-12-31
 */
@RestController
@RequestMapping("/logisticsOrder")
public class OrderLogisticsController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IGoodsService goodsService;
    @Resource
    private IPlatformOrderService platformOrderService;
    @Resource
    private IPlatformOrderGoodsService platformOrderGoodsService;

    @Resource
    private IPlatformOrderBiddingService platformOrderBiddingService;
    @Resource
    private ILogisticsOrderService logisticsOrderServices;
    @Resource
    private ILogisticsOrderGoodsService logisticsOrderGoodsService;
    @Resource
    private ITransportService transportService;
    @Resource
    private IAddressService addressService;
    @Resource
    private ITruckerOrderService truckerOrderService;




    /**
     * 物流公司-货源中心列表
     *
     * @param
     * @return
     */
    @GetMapping(value = "logisticsSuppList")
    public ResultData logisticsSuppList(@RequestParam(required = false) String addrFrom,
                                            @RequestParam(required = false) String addrTo,
                                            @RequestParam(required = false) String num,
                                            @RequestParam(required = false) String statusCode,//逗号隔开的  需要处理
                                            @RequestParam(required = false) String companyId,
                                            @RequestParam(required = false, defaultValue = "1") Integer page,
                                            @RequestParam(required = false, defaultValue = "10") Integer rows,
                                        @RequestParam(required = false, defaultValue = "") String userId) {
        try {

            //
            EntityWrapper<PlatformOrderEntity> platformEntityWrapper = new EntityWrapper<PlatformOrderEntity>();
            if (StringUtils.isNotEmpty(num)) {
                platformEntityWrapper.eq("num", num);
            }
            if (StringUtils.isNotEmpty(statusCode)) {
                String[] split = statusCode.split(",");
                platformEntityWrapper.in("status_code", split);
            }

            if (StringUtils.isNotEmpty(addrFrom)) {
                platformEntityWrapper.like("addr_from", addrFrom);
            }


            if (StringUtils.isNotEmpty(addrTo)) {
                platformEntityWrapper.like("addr_to", addrTo);
            }


            if (StringUtils.isNotEmpty(addrTo)) {
                platformEntityWrapper.like("addr_to", addrTo);
            }

            if (StringUtils.isNotEmpty(companyId)) {
                platformEntityWrapper.or().in("carrier_id", companyId).eq("status_code",Constants.ORDER_STATUS_DESIGNATE);
            }


            Page<PlatformOrderEntity> platformOrderPage = platformOrderService.selectPage(new Page<PlatformOrderEntity>(page, rows), platformEntityWrapper);
            List<PlatformOrderEntity> records = platformOrderPage.getRecords();
            List<OrderListVo> platformOrderListVos = new ArrayList<OrderListVo>() ;

            for (PlatformOrderEntity  platformOrderEntity: records) {
                //查询此单是否竞价过 大于0  就是竞价过
                int countType = platformOrderBiddingService.selectByCarrierIdAndOrderId(platformOrderEntity.getId(),companyId);
                if(countType>0)continue;

                OrderListVo  orderSupplyListVo = new OrderListVo();
                BeanMapper.copy(platformOrderEntity, orderSupplyListVo);

                String orderId = orderSupplyListVo.getId();
                List<PlatformOrderGoodsEntity> platformOrderGoodsEntities = platformOrderGoodsService.selectOrderByOrderId(orderId);
                //所有货品
                String goodName = Constants.DEFAULT_STRING;
                BigDecimal weight = new BigDecimal(0);
                GoodsEntity goodsBasic = new GoodsEntity();
                for (PlatformOrderGoodsEntity platformOrderGoodsEntity : platformOrderGoodsEntities) {
                    goodsBasic = goodsService.selectBaseGoodsByGoodsId(platformOrderGoodsEntity.getGoodsId());
                    //重量  名称
                    if (goodsBasic != null) {
                        goodName = goodsBasic.getName();
                    }
                }
                //查询商品名称-
                orderSupplyListVo.setGoodsName(goodName);
                orderSupplyListVo.setWeight(String.valueOf(weight));
                TransportEntity transportEntity = transportService.selectByOrderId(goodsBasic.getShipperOrderId());
                //地址
                if (transportEntity != null) {
                    AddressEntity from = addressService.selectById(transportEntity.getFromUserAddressId());
                    AddressEntity to = addressService.selectById(transportEntity.getToUserAddressId());
                    orderSupplyListVo.setAddressFrom(from);
                    orderSupplyListVo.setAddresTo(to);
                    BeanMapper.copy(transportEntity,orderSupplyListVo);
                    orderSupplyListVo.setUnloadPlanDateStr(DateFormatUtils.formatDate(transportEntity.getUnloadPlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    orderSupplyListVo.setUnloadRealDateStr(DateFormatUtils.formatDate(transportEntity.getUnloadPlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    orderSupplyListVo.setTakePlanDateStr(DateFormatUtils.formatDate(transportEntity.getTakePlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    orderSupplyListVo.setTakeRealDateStr(DateFormatUtils.formatDate(transportEntity.getTakePlanDate(), "yyyy-MM-dd HH:mm:ss"));
                }
                orderSupplyListVo.setId(orderId);
                orderSupplyListVo.setOrderType(Constants.USER_TYPE_OUTSIDE_PLATFORM);
                orderSupplyListVo.setGoodsWeight(platformOrderEntity.getGoodsWeight());
                orderSupplyListVo.setGoodsName(platformOrderEntity.getGoodsName());
                platformOrderListVos.add(orderSupplyListVo);
            }
            int platformCount = platformOrderService.selectCount(platformEntityWrapper);


            EntityWrapper<LogisticsOrderEntity> logisticsWrapper = new EntityWrapper<>();
            logisticsWrapper.in("status_code", Constants.ORDER_STATUS_DESIGNATE);

            if (StringUtils.isNotEmpty(num)) {
                logisticsWrapper.eq("num", num);
            }

            if (StringUtils.isNotEmpty(addrFrom)) {
                logisticsWrapper.like("addr_from", addrFrom);
            }

            if (StringUtils.isNotEmpty(addrTo)) {
                logisticsWrapper.like("addr_to", addrTo);
            }

            if (StringUtils.isNotEmpty(companyId)) {
                logisticsWrapper.in("carrier_id", companyId);
            }

            int logisticsCount = logisticsOrderServices.selectCount(logisticsWrapper);
            Page<LogisticsOrderEntity> logisticsOrderpPage = logisticsOrderServices.selectPage(new Page(page, rows), logisticsWrapper);
            ArrayList<OrderListVo> logisticsOrderListVos = Lists.newArrayList();
            List<LogisticsOrderEntity> list = logisticsOrderpPage.getRecords();
            for (LogisticsOrderEntity lo : list) {
                try {
                    OrderListVo vo = BeanMapper.map(lo, OrderListVo.class);
                    GoodsEntity goodsEntity = goodsService.selectBaseGoodsByLogisticsOrderId(lo.getId());
                    TransportEntity transportEntity = transportService.selectById(goodsEntity.getTransportId());
                    vo.setGoodsName(goodsEntity.getName());
                    vo.setWeight(String.valueOf(goodsEntity.getWeight()));
                    AddressEntity fAddressEntity = addressService.selectById(transportEntity.getFromUserAddressId());
                    AddressEntity tAddressEntity = addressService.selectById(transportEntity.getToUserAddressId());
                    vo.setAddressFrom(fAddressEntity);
                    vo.setAddresTo(tAddressEntity);
                    vo.setOrderType(Constants.USER_TYPE_OUTSIDE_COMPANY);
                    BeanMapper.copy(transportEntity,vo);
                    vo.setId(lo.getId());
                    vo.setUnloadPlanDateStr(DateFormatUtils.formatDate(transportEntity.getUnloadPlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    vo.setUnloadRealDateStr(DateFormatUtils.formatDate(transportEntity.getUnloadPlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    vo.setTakePlanDateStr(DateFormatUtils.formatDate(transportEntity.getTakePlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    vo.setTakeRealDateStr(DateFormatUtils.formatDate(transportEntity.getTakePlanDate(), "yyyy-MM-dd HH:mm:ss"));
                    logisticsOrderListVos.add(vo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("数据加工失败，物流公司运单编号为：{}==,,失败原因为{}", lo.getId(), e.getMessage());
                    return ResultData.result(false).setData(e);
                }
            }

            ArrayList<OrderListVo> orderListVos =new  ArrayList<OrderListVo>();
            orderListVos.addAll(logisticsOrderListVos);
            orderListVos.addAll(platformOrderListVos);


            return ResultData.result(true).setData(orderListVos).setTotalCount(platformCount+logisticsCount);
        } catch (Exception e) {
            logger.error("[OrderPlatformController]<== method[platformOrderBillList], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }



    /**
     * 物流公司-订单管理列表
     *
     * @param
     * @return
     */
    @GetMapping(value = "logisticsOrderList")
    public ResultData logisticsOrderList(@RequestParam(required = false) String addrFrom,
                                            @RequestParam(required = false) String addrTo,
                                            @RequestParam(required = false) String num,
                                            @RequestParam(required = false) String statusCode,//逗号隔开的  需要处理
                                            @RequestParam(required = false) String companyId,
                                            @RequestParam(required = false) String userId,
                                            @RequestParam(required = false, defaultValue = "0") String listType,//0 物流公司-订单管理列表  1,平台子订单列表
                                            @RequestParam(required = false, defaultValue = "1") Integer page,
                                            @RequestParam(required = false, defaultValue = "10") Integer rows) {
        try {
            EntityWrapper<LogisticsOrderEntity> logisticsWrapper = new EntityWrapper<>();
            //物流公司的订单管理
            if (listType.equals(Constants.DEFAULT_VAULE_ZERO)) {
                logisticsWrapper.ne("status_code", Constants.ORDER_STATUS_DESIGNATE);
            }

            if (StringUtils.isNotEmpty(statusCode)) {
                String[] split = statusCode.split(",");
                logisticsWrapper.in("status_code", split);
            }

            if (StringUtils.isNotEmpty(companyId)) {
                logisticsWrapper.in("carrier_id", companyId);
            }
            if (StringUtils.isNotEmpty(num)) {
                logisticsWrapper.eq("num", num);
            }

            if (StringUtils.isNotEmpty(addrFrom)) {
                logisticsWrapper.like("addr_from", addrFrom);
            }


            if (StringUtils.isNotEmpty(addrTo)) {
                logisticsWrapper.like("addr_to", addrTo);
            }

            if (StringUtils.isNotEmpty(userId)) {
                logisticsWrapper.like("user_id", userId);
            }

            int logisticsCount = logisticsOrderServices.selectCount(logisticsWrapper);
            Page<LogisticsOrderEntity> logisticsOrderpPage = logisticsOrderServices.selectPage(new Page(page, rows), logisticsWrapper);
            ArrayList<OrderListVo> logisticsOrderListVos = Lists.newArrayList();
            List<LogisticsOrderEntity> list = logisticsOrderpPage.getRecords();
            for (LogisticsOrderEntity lo : list) {
                try {
                    OrderListVo vo = BeanMapper.map(lo, OrderListVo.class);
                    GoodsEntity goodsEntity = goodsService.selectBaseGoodsByLogisticsOrderId(lo.getId());
                    TransportEntity transportEntity = transportService.selectById(goodsEntity.getTransportId());
                    AddressEntity fAddressEntity = addressService.selectById(transportEntity.getFromUserAddressId());
                    AddressEntity tAddressEntity = addressService.selectById(transportEntity.getToUserAddressId());
                    vo.setAddressFrom(fAddressEntity);
                    vo.setAddresTo(tAddressEntity);
                    vo.setOrderType(Constants.USER_TYPE_OUTSIDE_COMPANY);
                    vo.setWeight(String.valueOf(lo.getGoodsWeight()));
                    logisticsOrderListVos.add(vo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("数据加工失败，物流公司运单编号为：{}==,,失败原因为{}", lo.getId(), e.getMessage());
                    return ResultData.result(false).setData(e);
                }
            }


            return ResultData.result(true).setData(logisticsOrderListVos).setTotalCount(logisticsCount);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[logisticsOrderList], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }






    /**
     * 物流公司订单调度-指派（调度）
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "logisticsDispatchOrder")
    @Transactional
    public ResultData logisticsDispatchOrder(HttpServletRequest request, HttpServletResponse response) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            OrderDispatchVo orderDispatchVo = GsonQuick.toObject(receivePostJson, OrderDispatchVo.class);
            orderDispatchVo.setStatusCodeDesc("指派中");
            orderDispatchVo.setStatus(Integer.valueOf(Constants.ORDER_STATUS_DESIGNATE));
            Integer dispatchType = orderDispatchVo.getDispatchType();
            if (dispatchType == null) return ResultData.result(true).setMsg("请确认调度类型是否传值");
//            //201-指派中
//            if (Constants.USER_TYPE_INSIDE_DRIVER.equals(String.valueOf(dispatchType))) {
//                //司机指派单 直接生成运单
//                truckerOrderService.creatTruckerOrder(orderDispatchVo);
//            } else {
//                //物流公司  当前表继续插入数据
//
//
//            }
            logisticsOrderServices.creatLogisticsOrder(orderDispatchVo);
            List<String> goodsIds = orderDispatchVo.getGoodsIds();
            //更新关系表状态状态
            logisticsOrderGoodsService.upDataOrderGoodsService(goodsIds);
            //更新订单状态
            List<String> orderIds = orderDispatchVo.getOrderIds();
            logisticsOrderServices.updatelogisticsOrderStatus(orderIds,Constants.ORDER_WAITING_PICK_UP_GOODS,"待提货");

            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[logisticsDispatchOrder], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * 订单调度中-指派中-列表展示===物流公司运单列表展示
     *
     * @param statusCode
     * @return
     */
    @GetMapping(value = "orderList")
    public ResultData orderList(@RequestParam(required = false, defaultValue = "") String statusCode,
                                @RequestParam(required = false, defaultValue = "") String companyId,
                                @RequestParam(required = false, defaultValue = "") String userId,
                                @RequestParam(required = false, defaultValue = "1") Integer page,
                                @RequestParam(required = false, defaultValue = "10") Integer rows) {
        try {
            logger.info("[picture]==> method[orderList],物流公司运单列表展示 请求数据为：[{}]", statusCode, companyId);
            EntityWrapper<LogisticsOrderEntity> wrapper = new EntityWrapper<>();

            if (StringUtils.isNotEmpty(statusCode)) {
                String[] split = statusCode.split(",");
                wrapper.in("status_code", split);
            }

            if (StringUtils.isNotEmpty(companyId)) {
                wrapper.in("carrier_id", companyId);
            }

            if (StringUtils.isNotEmpty(userId)) {
                wrapper.in("user_id", userId);
            }
            int count = logisticsOrderServices.selectCount(wrapper);
            Page<LogisticsOrderEntity> logisticsOrderpPage = logisticsOrderServices.selectPage(new Page(page, rows), wrapper);

            ArrayList<OrderListVo> orderListVos = Lists.newArrayList();
            List<LogisticsOrderEntity> list = logisticsOrderpPage.getRecords();
            for (LogisticsOrderEntity lo : list) {
                try {
                    OrderListVo vo = BeanMapper.map(lo, OrderListVo.class);
                    GoodsEntity goodsEntity = goodsService.selectBaseGoodsByLogisticsOrderId(lo.getId());
                    TransportEntity transportEntity = transportService.selectById(goodsEntity.getTransportId());
                    vo.setGoodsName(lo.getGoodsName());
                    vo.setWeight(String.valueOf(lo.getGoodsWeight()));
                    vo.setCarriage(lo.getCarriage());
                    AddressEntity fAddressEntity = addressService.selectById(transportEntity.getFromUserAddressId());
                    AddressEntity tAddressEntity = addressService.selectById(transportEntity.getToUserAddressId());
                    vo.setAddressFrom(fAddressEntity);
                    vo.setAddresTo(tAddressEntity);
                    orderListVos.add(vo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("数据加工失败，物流公司运单编号为：{}==,,失败原因为{}", lo.getId(), e.getMessage());
                    return ResultData.result(false).setData(e);
                }
            }
            return ResultData.result(true).setTotalCount(count).setData(orderListVos);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[orderList], 物流公司运单列表展示失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * @param id
     * @return
     * @Title dispatchOrderList
     * @Description 运单详情
     */
    @GetMapping(value = "selectByOrderId")
    public ResultData selectByOrderId(@RequestParam(required = true) String id) {
        try {

            LogisticsOrderEntity logisticsOrderEntity = logisticsOrderServices.selectById(id);
            OrderbillInfoVo orderbillInfoVo = BeanMapper.map(logisticsOrderEntity, OrderbillInfoVo.class);

            List<GoodsEntity> goodsEntities = goodsService.selectGoodssByLogisticsOrderId(id,null);
            List<GoodsInfoVo> goodsInfoVos = BeanMapper.mapList(goodsEntities, GoodsInfoVo.class);

            GoodsEntity baseGoods = goodsService.selectBaseGoodsByLogisticsOrderId(id);
            //货品列表
            GoodsBaseVo goodsBaseVo = new GoodsBaseVo();
            if (baseGoods != null) {
                BeanMapper.copy(baseGoods, goodsBaseVo);
                goodsBaseVo.setWeight(new BigDecimal(logisticsOrderEntity.getGoodsWeight()));
                goodsBaseVo.setLeftWeight(new BigDecimal(logisticsOrderEntity.getGoodsWeight()));
                goodsBaseVo.setName(logisticsOrderEntity.getGoodsName());
                TransportEntity transportEtity = transportService.selectById(baseGoods.getTransportId());
                AddressEntity fAddressEntity = addressService.selectById(transportEtity.getFromUserAddressId());
                AddressEntity tAddressEntity = addressService.selectById(transportEtity.getToUserAddressId());
                orderbillInfoVo.setNote(transportEtity.getNote());
                orderbillInfoVo.setAddressFrom(fAddressEntity);
                orderbillInfoVo.setAddresTo(tAddressEntity);
                BeanMapper.copy(transportEtity, orderbillInfoVo);
                orderbillInfoVo.setUnloadPlanDateStr(DateFormatUtils.formatDate(transportEtity.getUnloadPlanDate(), "yyyy-MM-dd HH:mm:ss"));
              //  orderbillInfoVo.setUnloadRealDateStr(DateFormatUtils.formatDate(transportEtity.getUnloadRealDate(), "yyyy-MM-dd HH:mm:ss"));
                orderbillInfoVo.setTakePlanDateStr(DateFormatUtils.formatDate(transportEtity.getTakePlanDate(), "yyyy-MM-dd HH:mm:ss"));
              //  orderbillInfoVo.setTakeRealDateStr(DateFormatUtils.formatDate(transportEtity.getTakeRealDate(), "yyyy-MM-dd HH:mm:ss"));

            }
            orderbillInfoVo.setGoodsBaseVo(goodsBaseVo);
            orderbillInfoVo.setGoodsInfoVoS(goodsInfoVos);

            return ResultData.result(true).setData(orderbillInfoVo);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[orderList], 物流公司运单详情查询失败原因 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * @param request
     * @param response "95":"抢单中","96":"指派中","961":"拒绝接单","97":"竞价中","98":"待审核","99":"报价中","100":"待接单","101":"待提货",
     *                 "102":"运输中","103":"待确认","104":"已完成","105":"异常运单","106":"驳回运单","107":"待发布"
     * @return ResultData 返回类型
     * @throws
     * @Title logisticsBargain
     * @Description 改价或者app操作接单
     */
    @PostMapping(value = "update")
    public ResultData logisticsBargain(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        TruckerBackVo logisticsBargainDto = GsonQuick.toObject(receivePostJson, TruckerBackVo.class);
        try {
            if (StringUtils.isBlank(logisticsBargainDto.getId())) {
                return ResultData.result(false).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC);
            }
            LogisticsOrderEntity logisticsOrderEntity = BeanMapper.map(logisticsBargainDto, LogisticsOrderEntity.class);
            LogisticsOrderEntity loe = logisticsOrderServices.selectById(logisticsOrderEntity.getId());
            //判断是不是指派中的订单
            if (!StringUtils.equals(Constants.ORDER_STATUS_DESIGNATE, loe.getStatusCode())) {
                return ResultData.result(false).setCode(MsgCode.ORDER_STATUS_NOT_DESIGNATE).setMsg(MsgCode.ORDER_STATUS_NOT_DESIGNATE_DESC);
            }

            logisticsOrderEntity.setStatusCode(logisticsBargainDto.getStatusCode());
            if (StringUtils.isNoneBlank(logisticsBargainDto.getReason())) {
                logisticsOrderEntity.setReason(logisticsBargainDto.getReason());
            }

            //拒绝要回退状态的
            if (StringUtils.equals(Constants.ORDER_STATUS_REFUSE_ORDER, loe.getStatusCode())) {
                List<GoodsEntity> goods = goodsService.selectGoodssByLogisticsOrderId(logisticsBargainDto.getId(),null);
                for (GoodsEntity goodsEntity : goods) {
                    String goodsId = goodsEntity.getId();
                    goodsService.updateGoodssStatus(goodsId, Constants.GOODS_WAIT_DESIGNATE);

                    EntityWrapper<PlatformOrderGoodsEntity> wrapper = new EntityWrapper<>();
                    wrapper.eq("goods_id", goodsId);
                    PlatformOrderGoodsEntity platformOrderGoods = platformOrderGoodsService.selectOne(wrapper);
                    List<GoodsEntity> goodsEntities = goodsService.selectGoodssByPlatFormOrderId(platformOrderGoods.getId(), "");
                    if (CollectionUtils.isEmpty(goodsEntities)) {
                        PlatformOrderEntity platformOrderEntity = new PlatformOrderEntity();
                        platformOrderEntity.setId(platformOrderGoods.getPlatformOrderId());
                        platformOrderEntity.setStatusCode("107");
                        platformOrderEntity.setStatusCodeDesc("待发布");
                        platformOrderService.updateById(platformOrderEntity);
                    }
                }
            }
            logisticsOrderServices.updateById(logisticsOrderEntity);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[logisticsBargain], 更新运单失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * @param request
     * @param response
     * @return ResultData 返回类型
     * @throws
     * @Title logisticsBargain
     * @Description 上传提货单，并确认提货
     */
    @PostMapping(value = "logisticsTakeGoods")
    public ResultData logisticsTakeGoods(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        TruckerBackVo logisticsOrderDto = GsonQuick.toObject(receivePostJson, TruckerBackVo.class);
        try {


            if (StringUtils.isBlank(logisticsOrderDto.getId())) {
                return ResultData.result(false).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC);
            }
            if (StringUtils.isBlank(logisticsOrderDto.getDeliveryOrderUrl())) {
                return ResultData.result(false).setCode(MsgCode.DELIVERY_ORDER_URL_NOT_EXIST).setMsg(MsgCode.DELIVERY_ORDER_URL_NOT_EXIST_DESC);
            }
            LogisticsOrderEntity logisticsOrderEntity = BeanMapper.map(logisticsOrderDto, LogisticsOrderEntity.class);
            LogisticsOrderEntity sLogisticsOrderEntity = logisticsOrderServices.selectById(logisticsOrderEntity.getId());
            //判断是不是已接单的状态
            if (!StringUtils.equals(Constants.ORDER_WAITING_PICK_UP_GOODS, sLogisticsOrderEntity.getStatusCode())) {
                return ResultData.result(false).setCode(MsgCode.ORDER_DATA_ERROR).setMsg(MsgCode.ORDER_DATA_ERROR_DESC);
            }
            logisticsOrderEntity.setStatusCode(Constants.ORDER_IN_TRANSIT);
            logisticsOrderServices.updateById(logisticsOrderEntity);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[logisticsTakeGoods],上传提货单，并确认提货 失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * @param request
     * @param response
     * @return ResultData 返回类型
     * @throws
     * @Title logisticsBargain
     * @Description 上传回执单，等待审核
     */
    @PostMapping(value = "logisticsTakeReceipt")
    public ResultData logisticsTakeReceipt(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        TruckerBackVo logisticsOrderDto = GsonQuick.toObject(receivePostJson, TruckerBackVo.class);
        try {
            if (StringUtils.isBlank(logisticsOrderDto.getId())) {
                return ResultData.result(false).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC);
            }
            if (StringUtils.isBlank(logisticsOrderDto.getReceiptUrl())) {
                return ResultData.result(false).setCode(MsgCode.RECEIPT_URL_NOT_EXIST).setMsg(MsgCode.RECEIPT_URL_NOT_EXIST_DESC);
            }
            LogisticsOrderEntity logisticsOrderEntity = BeanMapper.map(logisticsOrderDto, LogisticsOrderEntity.class);
            LogisticsOrderEntity sLogisticsOrderEntity = logisticsOrderServices.selectById(logisticsOrderEntity.getId());
            //判断是不是运输中
            if (!StringUtils.equals(Constants.ORDER_IN_TRANSIT, sLogisticsOrderEntity.getStatusCode())) {
                return ResultData.result(false).setCode(MsgCode.ORDER_DATA_ERROR).setMsg(MsgCode.ORDER_DATA_ERROR_DESC);
            }
            logisticsOrderEntity.setStatusCode(Constants.ORDER_WAIT_FOR_CONFIRMATION);
            logisticsOrderServices.updateById(logisticsOrderEntity);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[logisticsTakeGoods],上传提货单，并确认提货 失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * @param request
     * @param response
     * @return ResultData 返回类型
     * @throws
     * @Title logisticsBargain
     * @Description 审核运单
     */
    @PostMapping(value = "logisticsAudit")
    public ResultData logisticsAudit(HttpServletRequest request, HttpServletResponse response) {
        String receivePostJson = RequestUtil.receivePostJson(request);
        TruckerBackVo logisticsOrderDto = GsonQuick.toObject(receivePostJson, TruckerBackVo.class);
        try {

            if (StringUtils.isBlank(logisticsOrderDto.getId())) {
                return ResultData.result(false).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC);
            }
            LogisticsOrderEntity logisticsOrderEntity = BeanMapper.map(logisticsOrderDto, LogisticsOrderEntity.class);
            LogisticsOrderEntity sLogisticsOrderEntity = logisticsOrderServices.selectById(logisticsOrderEntity.getId());
            //判断是不是运输中
            if (!StringUtils.equals(Constants.ORDER_WAIT_FOR_CONFIRMATION, sLogisticsOrderEntity.getStatusCode())) {
                return ResultData.result(false).setCode(MsgCode.ORDER_DATA_ERROR).setMsg(MsgCode.ORDER_DATA_ERROR_DESC);
            }
            logisticsOrderEntity.setStatusCode(logisticsOrderDto.getStatusCode());
            logisticsOrderServices.updateById(logisticsOrderEntity);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[logisticsTakeGoods],上传提货单，并确认提货 失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * 物流公司  接单  驳回
     *
     * @param
     * @return
     */
    @PostMapping(value = "logisticsChoiceOrder")
    public ResultData logisticsChoiceOrder(HttpServletRequest request) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            OrderBiddingVo platformOrderBiddingVo = GsonQuick.toObject(receivePostJson, OrderBiddingVo.class);

            Date now = new Date();
            //公司指派来的单 (接单,驳回)
            String orderType = platformOrderBiddingVo.getOrderType();
            Integer status = platformOrderBiddingVo.getStatus();
            if (Constants.USER_TYPE_OUTSIDE_COMPANY.equals(orderType)) {
                LogisticsOrderEntity logisticsOrderEntity = logisticsOrderServices.selectById(platformOrderBiddingVo.getOrderId());
                if (logisticsOrderEntity == null) ResultData.result(true);

                logisticsOrderEntity.setStatusCode(String.valueOf(status));
                logisticsOrderEntity.setStatusCodeDesc(platformOrderBiddingVo.getStatusCodeDesc());
                logisticsOrderEntity.setCarrierId(platformOrderBiddingVo.getCarrierId());
                logisticsOrderEntity.setCarrierName(platformOrderBiddingVo.getCarrierName());
                logisticsOrderEntity.setCarrierMobile(platformOrderBiddingVo.getCarrierMobile());
                logisticsOrderEntity.setRemarks(platformOrderBiddingVo.getRemarks());
                Double carriage = logisticsOrderEntity.getCarriage();
                if (carriage != null && carriage > 0) {
                    logisticsOrderEntity.setCarriage(carriage);
                }
                logisticsOrderEntity.setUpdateTime(now);
                platformOrderBiddingVo.setUserId(logisticsOrderEntity.getUserId());
                logisticsOrderServices.insertOrUpdate(logisticsOrderEntity);
                //如果是接单 需要创建订单
            //    if(!Constants.ORDER_STATUS_REFUSE_ORDER.equals(String.valueOf(status))){
             //       platformOrderBiddingVo.setStatus(Constants.ORDER_STATUS_CODE_RELEASE_GOODS);
             //       platformOrderBiddingVo.setStatusCodeDesc("待调度");
               //     logisticsOrderServices.creatLogisticsOrderLTOL(platformOrderBiddingVo);
                //}

            }

            //平台指派来的单 (接单,驳回)
            if (Constants.USER_TYPE_OUTSIDE_PLATFORM.equals(orderType)) {
                PlatformOrderEntity platformOrderEntity = platformOrderService.selectById(platformOrderBiddingVo.getOrderId());
                if (platformOrderEntity == null) ResultData.result(true);
                platformOrderEntity.setStatusCode(String.valueOf(status));
                platformOrderEntity.setStatusCodeDesc(platformOrderBiddingVo.getStatusCodeDesc());
                platformOrderEntity.setCarrierId(platformOrderBiddingVo.getCarrierId());
                platformOrderEntity.setCarrier(platformOrderBiddingVo.getCarrierName());
                platformOrderEntity.setCarrierMobile(platformOrderBiddingVo.getCarrierMobile());
                platformOrderEntity.setRemarks(platformOrderBiddingVo.getRemarks());
                Double carriage = platformOrderEntity.getCarriage();
                if (carriage != null && carriage > 0) {
                    platformOrderEntity.setCarriage(carriage);
                }
                platformOrderEntity.setUpdateTime(now);
                platformOrderBiddingVo.setUserId(platformOrderEntity.getUserId());
                platformOrderService.insertOrUpdate(platformOrderEntity);
                //如果是接单 需要创建订单
                if(!Constants.ORDER_STATUS_REFUSE_ORDER.equals(String.valueOf(status))){
                    platformOrderBiddingVo.setStatus(Constants.ORDER_STATUS_CODE_RELEASE_GOODS);
                    platformOrderBiddingVo.setStatusCodeDesc("待调度");
                    platformOrderBiddingVo.setGoodsName(platformOrderEntity.getGoodsName());
                    platformOrderBiddingVo.setGoodsWeight(platformOrderEntity.getGoodsWeight());
                    platformOrderBiddingVo.setAmount(platformOrderEntity.getAmountDeal());
                    platformOrderBiddingVo.setCarriage(platformOrderEntity.getCarriageDeal());
                    logisticsOrderServices.creatLogisticsOrder(platformOrderBiddingVo);
                }
            }



            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[platformChoiceOrder], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

    /**
     * 更新平台订单状态  ( 物流公司 续选 )
     *
     * @param
     * @return
     */
    @PostMapping(value = "updateLogisticsOrderStatus")
    public ResultData updateLogisticsOrderStatus(HttpServletRequest request) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            ChangeStatusVo changeStatusVo = GsonQuick.toObject(receivePostJson, ChangeStatusVo.class);
            //更新状态
            logisticsOrderServices.updateplatformOrderStatus(changeStatusVo);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[updateSupplyOrderStatus], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }


    /**
     * 物流公司改价
     *
     * @param
     * @return
     */
    @PostMapping(value = "logisticsOrderChangeCarriage")
    public ResultData logisticsOrderChangeCarriage(HttpServletRequest request) {
        try {
            String receivePostJson = RequestUtil.receivePostJson(request);
            PlatformOrderChangeCarriageVo platformOrderChangeCarriageVo = GsonQuick.toObject(receivePostJson, PlatformOrderChangeCarriageVo.class);
            Date now = new Date();
            LogisticsOrderEntity logisticsOrderEntity = logisticsOrderServices.selectById(platformOrderChangeCarriageVo.getOrderId());
            if (logisticsOrderEntity == null) ResultData.result(true);
            logisticsOrderEntity.setCarriageDeal(platformOrderChangeCarriageVo.getCarriage());
            Double carriage = logisticsOrderEntity.getCarriage();
            if(carriage<=0){
                carriage=1d;
            }
            double a = logisticsOrderEntity.getAmount() / carriage;
            logisticsOrderEntity.setAmountDeal(platformOrderChangeCarriageVo.getCarriage() * a);
            logisticsOrderEntity.setUpdateTime(now);
            logisticsOrderServices.insertOrUpdate(logisticsOrderEntity);
            return ResultData.result(true);
        } catch (Exception e) {
            logger.error("[OrderLogisticsController]<== method[logisticsOrderChangeCarriage], 更新状态失败 :[{}]", e.getMessage());
            e.printStackTrace();
            return ResultData.result(false).setData(e);
        }
    }

}
